﻿using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using LeaRun.Application.Busines.AppManage;
using LeaRun.Application.Busines.AuthorizeManage;
using LeaRun.Application.Code;
using LeaRun.Application.Entity.AppManage;
using LeaRun.Application.Entity.AuthorizeManage;
using System;
using LeaRun.Util;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web.Mvc;

namespace LeaRun.Application.Web.Areas.AppManage.Controllers
{
    /// <summary>
    /// 版 本 6.1
    /// Copyright (c) 2013-2016 上海力软信息技术有限公司
    /// 创建人：佘赐雄
    /// 日 期：2015.11.20 13:32
    /// 描 述：
    /// </summary>
    public class AppProjectsController : MvcControllerBase
    {
        private App_ProjectBLL app_projectbll = new App_ProjectBLL();
        private App_TemplatesBLL app_templatebll = new App_TemplatesBLL();
        public ActionResult DownFile(string filename)
        {
            this.app_projectbll.DownFile(filename);
            return this.Success("下载成功。");
        }
        [HttpGet]
        public ActionResult GetFormJson(string keyValue)
        {
            App_ProjectEntity project = this.app_projectbll.GetEntity(keyValue);
            IEnumerable<App_TemplatesEntity> list = this.app_templatebll.GetList(keyValue);
            var data = new
            {
                project = project,
                templates = list
            };
            return this.ToJsonResult(data);
        }
        [HttpGet]
        public ActionResult GetListJson(string queryJson)
        {
            IEnumerable<App_ProjectEntity> list = this.app_projectbll.GetList(queryJson);
            return this.ToJsonResult(list);
        }
        [HttpGet]
        public ActionResult Index()
        {
            return base.View();
        }
        public ActionResult DownForm(string keyValue, App_ProjectEntity entity)
        {
            List<App_TemplatesEntity> arg_D7_0 = entity.F_Templates;
            string text = "";
            string newValue = "";
            string b = "";
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder stringBuilder2 = new StringBuilder();
            StringBuilder stringBuilder3 = new StringBuilder();
            string text2 = entity.F_Name + DateTime.Now.ToString("yyyyMMddHHssmm");
            string path = base.Server.MapPath("/templates/" + text2 + "/templates/");
            string path2 = base.Server.MapPath("/templates/" + text2 + "/js/");
            string str = "/templates/" + text2 + "/templates/";
            string str2 = "/templates/" + text2 + "/js/";
            string newValue2 = "";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            if (!Directory.Exists(path2))
            {
                Directory.CreateDirectory(path2);
            }
            foreach (App_TemplatesEntity current in arg_D7_0)
            {
                App_ContentEntity app_ContentEntity = current.F_Content.ToObject<App_ContentEntity>();
                if (current.F_Type == "Page")
                {
                    if (stringBuilder.ToString() != "")
                    {
                        StringBuilder stringBuilder4 = new StringBuilder();
                        using (StreamReader streamReader = new StreamReader(base.Server.MapPath("/templates/app/PageTemplate.html"), Encoding.GetEncoding("utf-8")))
                        {
                            stringBuilder4 = stringBuilder4.Append(streamReader.ReadToEnd());
                            streamReader.Close();
                        }
                        stringBuilder4 = stringBuilder4.Replace("{PageTitle}", newValue);
                        stringBuilder4 = stringBuilder4.Replace("{PageContent}", stringBuilder.ToString());
                        using (FileStream fileStream = new FileInfo(base.Server.MapPath(str + text + ".html")).OpenWrite())
                        {
                            StreamWriter expr_1C5 = new StreamWriter(fileStream, Encoding.UTF8);
                            expr_1C5.WriteLine(stringBuilder4);
                            expr_1C5.Flush();
                            expr_1C5.Close();
                        }
                    }
                    stringBuilder.Remove(0, stringBuilder.Length);
                    newValue2 = current.F_Id;
                    text = "page" + current.F_Id;
                    text = text.Replace("-", "");
                    b = current.F_Id;
                    newValue = current.F_Name;
                }
                if (current.F_Type == "Component" && current.F_Value != "lrTab" && current.F_Parent == b)
                {
                    if (current.F_Value == "lrHeader")
                    {
                        stringBuilder.Append(string.Concat(new string[]
						{
							"<",
							app_ContentEntity.size,
							" style=\"color:",
							app_ContentEntity.color,
							"; text-align:",
							app_ContentEntity.align,
							";\">",
							app_ContentEntity.text,
							"</",
							app_ContentEntity.size,
							">"
						}));
                    }
                    else
                    {
                        if (current.F_Value == "lrList3")
                        {
                            stringBuilder.Append(string.Concat(new string[]
							{
								"<div class=\"list lr-list-type3\"><ion-item class=\"item item-icon-left\"><i class=\"icon ",
								app_ContentEntity.icon,
								" ",
								app_ContentEntity.color,
								"\" ></i> <span>",
								app_ContentEntity.name,
								"</span></ion-item></div>"
							}));
                        }
                        else
                        {
                            if (current.F_Value == "lrList4")
                            {
                                stringBuilder.Append(string.Concat(new string[]
								{
									"<div class=\"list lr-list-type3\"><ion-item class=\"item item-icon-left\"><i class=\"icon ",
									app_ContentEntity.icon,
									" ",
									app_ContentEntity.color,
									"\" ></i> <span>",
									app_ContentEntity.name,
									"</span></ion-item></div>"
								}));
                            }
                            else
                            {
                                if (current.F_Value == "lrInput")
                                {
                                    stringBuilder.Append("<label class=\"item item-input\"><input type=\"text\" placeholder=\"" + app_ContentEntity.placeholder + "\"></label>");
                                }
                                else
                                {
                                    if (current.F_Value == "lrParagraph")
                                    {
                                        stringBuilder.Append(string.Concat(new string[]
										{
											"<p style=\"color:",
											app_ContentEntity.color,
											";font-size:",
											app_ContentEntity.size,
											";text-align:",
											app_ContentEntity.align,
											";\">",
											app_ContentEntity.content,
											"</p>"
										}));
                                    }
                                    else
                                    {
                                        if (current.F_Value == "lrBtn")
                                        {
                                            stringBuilder.Append(string.Concat(new string[]
											{
												"<button style=\"color:",
												app_ContentEntity.color,
												";font-size:",
												app_ContentEntity.size,
												";text-align:",
												app_ContentEntity.align,
												";font-weight:500;\" class=\"button button-defaultbutton-standardbutton-positive\">",
												app_ContentEntity.text,
												"</button>"
											}));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (current.F_Value == "lrTabs")
                {
                    stringBuilder3.Append(".state('tab', {\r\n");
                    stringBuilder3.Append("url: '/tab',\r\n");
                    stringBuilder3.Append("abstract: true,\r\n");
                    stringBuilder3.Append("templateUrl: 'templates/tabs.html',\r\n");
                    stringBuilder3.Append("controller: 'lrTabsCtrl'\r\n");
                    stringBuilder3.Append("})");
                }
                else
                {
                    if (current.F_Value == "lrTab")
                    {
                        stringBuilder3.Append(".state('tab" + current.F_Id + "', {\r\n");
                        stringBuilder3.Append("url: '/',\r\n");
                        stringBuilder3.Append("views: {\r\n");
                        stringBuilder3.Append("'tab-home': {\r\n");
                        stringBuilder3.Append("templateUrl: 'templates/.html'\r\n");
                        stringBuilder3.Append("}\r\n");
                        stringBuilder3.Append("}\r\n");
                        stringBuilder3.Append("})\r\n");
                        text = "tabs";
                        if (current.F_Name == "首页")
                        {
                            stringBuilder2.Append("<ion-tab title=\"首页\" icon-on=\"ion-ios-home\" icon-off=\"ion-ios-home-outline\" href=\"#/tab/DefaultPage\">\r\n");
                            stringBuilder2.Append("<ion-nav-view name=\"tab-" + current.F_Id + "\"></ion-nav-view>");
                            stringBuilder2.Append("</ion-tab>\r\n");
                        }
                        else
                        {
                            if (current.F_Name == "实例")
                            {
                                stringBuilder2.Append("<ion-tab title=\"实例\" icon-on=\"ion-ios-book\" icon-off=\"ion-ios-book-outline\" href=\"#/tab/DefaultPage\">\r\n");
                                stringBuilder2.Append("<ion-nav-view name=\"tab-" + current.F_Id + "\"></ion-nav-view>");
                                stringBuilder2.Append("</ion-tab>\r\n");
                            }
                            else
                            {
                                if (current.F_Name == "通知")
                                {
                                    stringBuilder2.Append("<ion-tab title=\"通知\" icon-on=\"ion-ios-bell\" icon-off=\"ion-ios-bell-outline\" href=\"#/tab/DefaultPage\">\r\n");
                                    stringBuilder2.Append("<ion-nav-view name=\"tab-" + current.F_Id + "\"></ion-nav-view>");
                                    stringBuilder2.Append("</ion-tab>\r\n");
                                }
                                else
                                {
                                    if (current.F_Name == "我的")
                                    {
                                        stringBuilder2.Append("<ion-tab title=\"我的\" icon-on=\"ion-ios-person\" icon-off=\"ion-ios-person-outline\" href=\"#/tab/DefaultPage\">\r\n");
                                        stringBuilder2.Append("<ion-nav-view name=\"tab-" + current.F_Id + "\"></ion-nav-view>");
                                        stringBuilder2.Append("</ion-tab>\r\n");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            StringBuilder stringBuilder5 = new StringBuilder();
            using (StreamReader streamReader2 = new StreamReader(base.Server.MapPath("/templates/app/tabs.html"), Encoding.GetEncoding("utf-8")))
            {
                stringBuilder5 = stringBuilder5.Append(streamReader2.ReadToEnd());
                streamReader2.Close();
            }
            stringBuilder5 = stringBuilder5.Replace("{PageContent}", stringBuilder2.ToString());
            using (FileStream fileStream2 = new FileInfo(base.Server.MapPath(str + text + ".html")).OpenWrite())
            {
                StreamWriter expr_7D1 = new StreamWriter(fileStream2, Encoding.UTF8);
                expr_7D1.WriteLine(stringBuilder5);
                expr_7D1.Flush();
                expr_7D1.Close();
            }
            stringBuilder5.Remove(0, stringBuilder5.Length);
            using (StreamReader streamReader3 = new StreamReader(base.Server.MapPath("/templates/app/learun-app.js"), Encoding.GetEncoding("utf-8")))
            {
                stringBuilder5 = stringBuilder5.Append(streamReader3.ReadToEnd());
                streamReader3.Close();
            }
            using (FileStream fileStream3 = new FileInfo(base.Server.MapPath(str2 + "learun-app.js")).OpenWrite())
            {
                StreamWriter expr_877 = new StreamWriter(fileStream3, Encoding.UTF8);
                expr_877.WriteLine(stringBuilder5);
                expr_877.Flush();
                expr_877.Close();
            }
            stringBuilder5.Remove(0, stringBuilder5.Length);
            using (StreamReader streamReader4 = new StreamReader(base.Server.MapPath("/templates/app/learun-controllers.js"), Encoding.GetEncoding("utf-8")))
            {
                stringBuilder5 = stringBuilder5.Append(streamReader4.ReadToEnd());
                streamReader4.Close();
            }
            stringBuilder5 = stringBuilder5.Replace("{FID}", newValue2);
            using (FileStream fileStream4 = new FileInfo(base.Server.MapPath(str2 + "learun-controllers.js")).OpenWrite())
            {
                StreamWriter expr_92D = new StreamWriter(fileStream4, Encoding.UTF8);
                expr_92D.WriteLine(stringBuilder5);
                expr_92D.Flush();
                expr_92D.Close();
            }
            stringBuilder5.Remove(0, stringBuilder5.Length);
            stringBuilder5 = new StringBuilder();
            using (StreamReader streamReader5 = new StreamReader(base.Server.MapPath("/templates/app/learun-uirouter.js"), Encoding.GetEncoding("utf-8")))
            {
                stringBuilder5 = stringBuilder5.Append(streamReader5.ReadToEnd());
                streamReader5.Close();
            }
            stringBuilder5 = stringBuilder5.Replace("{RouterStr}", stringBuilder3.ToString());
            using (FileStream fileStream5 = new FileInfo(base.Server.MapPath(str2 + "learun-uirouter.js")).OpenWrite())
            {
                StreamWriter expr_9EF = new StreamWriter(fileStream5, Encoding.UTF8);
                expr_9EF.WriteLine(stringBuilder5);
                expr_9EF.Flush();
                expr_9EF.Close();
            }
            AppProjectsController.ZipDirectory(base.Server.MapPath("/templates/" + text2), base.Server.MapPath("/templates/"), "", false);
            var data = new
            {
                path = text2
            };
            return this.ToJsonResult(data);
        }
        public static void ZipDirectory(string DirectoryToZip, string ZipedPath, string ZipedFileName = "", bool IsEncrypt = true)
        {
            if (!Directory.Exists(DirectoryToZip))
            {
                throw new FileNotFoundException("指定的目录: " + DirectoryToZip + " 不存在!");
            }
            using (FileStream fileStream = System.IO.File.Create(string.IsNullOrEmpty(ZipedFileName) ? (ZipedPath + "\\" + new DirectoryInfo(DirectoryToZip).Name + ".zip") : (ZipedPath + "\\" + ZipedFileName + ".zip")))
            {
                using (ZipOutputStream zipOutputStream = new ZipOutputStream(fileStream))
                {
                    if (IsEncrypt)
                    {
                        zipOutputStream.Password = "123";
                    }
                    AppProjectsController.ZipSetp(DirectoryToZip, zipOutputStream, "");
                }
            }
        }
        private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath)
        {
            if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar)
            {
                strDirectory += Path.DirectorySeparatorChar.ToString();
            }
            Crc32 crc = new Crc32();
            string[] fileSystemEntries = Directory.GetFileSystemEntries(strDirectory);
            for (int i = 0; i < fileSystemEntries.Length; i++)
            {
                string text = fileSystemEntries[i];
                if (Directory.Exists(text))
                {
                    string text2 = parentPath + text.Substring(text.LastIndexOf("\\") + 1);
                    text2 += "\\";
                    AppProjectsController.ZipSetp(text, s, text2);
                }
                else
                {
                    using (FileStream fileStream = System.IO.File.OpenRead(text))
                    {
                        byte[] array = new byte[fileStream.Length];
                        fileStream.Read(array, 0, array.Length);
                        ZipEntry zipEntry = new ZipEntry(parentPath + text.Substring(text.LastIndexOf("\\") + 1));
                        zipEntry.DateTime = DateTime.Now;
                        zipEntry.Size = fileStream.Length;
                        fileStream.Close();
                        crc.Reset();
                        crc.Update(array);
                        zipEntry.Crc = crc.Value;
                        s.PutNextEntry(zipEntry);
                        s.Write(array, 0, array.Length);
                    }
                }
            }
        }
        [AjaxOnly(false), HttpPost, ValidateAntiForgeryToken]
        public ActionResult RemoveForm(string keyValue)
        {
            this.app_projectbll.RemoveForm(keyValue);
            return this.Success("删除成功。");
        }
        [HttpPost]
        public ActionResult SaveForm(string keyValue, App_ProjectEntity entity)
        {
            List<App_TemplatesEntity> f_Templates = entity.F_Templates;
            this.app_projectbll.SaveForm(keyValue, entity, f_Templates);
            return this.Success("操作成功。");
        }
    }
}
